<template>
  <a-modal
    title="请选择登录机构"
    v-model:visible="openModal"
    :mask-closable="false"
    unmount-on-close
    :closable="false"
    title-align="start"
    width="800px"
  >
    <a-table
      v-if="sysList.length > 0"
      :loading="loading"
      :columns="columns"
      :data="sysList"
      :row-selection="rowSelection"
      v-model:selected-keys="ids"
      row-key="deptId"
      :pagination="{
        total: total,
        current: queryParams.pageNum,
        pageSize: queryParams.pageSize,
      }"
      @page-change="tablePageChange"
      @row-click="
        (row) => {
          ids = [row.deptId];
        }
      "
    ></a-table>
    <template #footer>
      <a-row justify="center">
        <a-button
          type="primary"
          @click="intoSystem"
          :loading="okLoading"
          :disabled="ids.length !== 1"
        >
          进入系统
        </a-button>
      </a-row>
    </template>
  </a-modal>
</template>

<script setup lang="ts">
  import {
    ref,
    reactive,
    computed,
    watch,
    defineProps,
    defineEmits,
  } from 'vue';
  import { tempTokenGetDeptList } from '@/api/login';

  // Props 定义
  interface Props {
    open: boolean;
    tempToken: string;
  }

  const props = defineProps<Props>();

  // Emits 定义
  const emits = defineEmits<{
    (event: 'intoSystem', deptId: number): void;
    (event: 'update:open', value: boolean): void;
  }>();

  // 选择设置
  const rowSelection = reactive({
    type: 'radio',
  });

  const openModal = computed(() => props.open);
  const loading = ref(false);
  const okLoading = ref(false);
  const ids = ref<number[]>([]);
  const total = ref(0);
  const queryParams = ref({
    pageNum: 1,
    pageSize: 5,
  });

  // 表格列定义
  const columns = ref([
    {
      title: '机构名称',
      dataIndex: 'deptName',
    },
    {
      title: '管理员姓名',
      dataIndex: 'realName',
    },
  ]);

  // 数据列表
  const sysList = ref<
    {
      deptId: number;
      deptName: string;
      realName: string;
    }[]
  >([]);

  watch(
    () => props.open,
    (newVal) => {
      if (newVal) {
        ids.value = [];
        handleQuery();
      }
    }
  );

  function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
  }

  function getList() {
    loading.value = true;
    tempTokenGetDeptList({ tempToken: props.tempToken }).then((response) => {
      const records = response.data.result.records;
      sysList.value = records.map((item: any) => ({
        deptId: item.deptId,
        deptName: item.deptName,
        realName: item.realName,
      }));
      total.value = response.data.result.total;
      loading.value = false;
    });
  }

  function tablePageChange(pageNum: number) {
    queryParams.value.pageNum = pageNum;
    getList();
  }

  function intoSystem() {
    emits('intoSystem', ids.value[0]);
    emits('update:open', false);
  }
</script>

<style scoped>
  /* Add your styles here */
</style>
